import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import Vue from "vue";
import { Loading } from "element-ui";

// 导出页面为PDF格式---使用插件html2canvas和jspdf插件
export function exportPDF(titleName, id) {
  document.body.scrollTop = document.documentElement.scrollTop = 0;
  let el = document.querySelector(`#${id}`);
  var clientH = el.clientHeight;
  el.style.height = el.scrollHeight + "px"; //把要导出的元素高度设置为滚动高度

  let obj = {
    lock: true,
    text: "Loading",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)",
  };

  // const loading = Loading.service(obj);

  html2canvas(el, {
    allowTaint: true,
    useCORS: true,
    dpi: 120, // 图片清晰度问题
    background: "#142D42", //如果指定的div没有设置背景色会默认成黑色,这里是个坑
    y: 0,
  }).then((canvas) => {
    console.log(canvas, "canvas");
    document.getElementById("messageBox").appendChild(canvas);
    // return;
    console.log(1);
    var currentPage = 1;
    //未生成pdf的html页面高度
    var leftHeight = canvas.height;
    var a4Width = 576;
    var a4Height = 772.89; //A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
    //一页pdf显示html页面生成的canvas高度;
    var a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height);
    // var a4HeightRef = 276;
    // console.log(2,a4HeightRef);
    //pdf页面偏移
    var position = 1;
    // console.log(canvas,'canvas');
    var pageData = canvas.toDataURL("image/jpeg", 1.0);
    // console.log(pageData,'pageData');
    var pdf = new jsPDF("p", "pt", "a4"); //A4纸，纵向
    // console.log(pdf,'pdf');
    pdf.addFont("simkai-normal.ttf", "simkai", "normal");
    pdf.setFont("simkai");
    // console.log(3);
    // pdf.setFontSize(20);
    pdf.setFontSize(16);
    // console.log(3);
    var index = 1,
      canvas1 = document.createElement("canvas"),
      height;
    // console.log(3);
    pdf.setDisplayMode("fullwidth", "continuous", "FullScreen");
    function createImpl(canvas) {
      // console.log(1);
      if (leftHeight > 0) {
        index++;
        var checkCount = 0;
        if (leftHeight > a4HeightRef) {
          var i = position + a4HeightRef;
          for (i = position + a4HeightRef; i >= position; i--) {
            var isWrite = true;
            for (var j = 0; j < canvas.width; j++) {
              var c = canvas.getContext("2d").getImageData(j, i, 1, 1).data;
              // console.log(checkCount);
              // if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
              if (c[0] == 255 && c[1] == 0 && c[2] == 0) {
                isWrite = false;

                // console.log(c, "red");
                pdf.addPage();
                break;
              }
            }
            if (isWrite) {
              checkCount++;
              if (checkCount >= 10) {
                break;
              }
            } else {
              checkCount = 0;
            }
          }
          height =
            Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
          if (height <= 0) {
            height = a4HeightRef;
          }
        } else {
          height = leftHeight;
        }
        canvas1.width = canvas.width;
        canvas1.height = height;
        var ctx = canvas1.getContext("2d");
        ctx.drawImage(
          canvas,
          0,
          position,
          canvas.width,
          height,
          0,
          0,
          canvas.width,
          height
        );
        var pageHeight = Math.round((a4Width / canvas.width) * height);
        if (position != 0) {
          pdf.addPage();
        }
        pdf.addImage(
          canvas1.toDataURL("image/jpeg", 1.0),
          "JPEG",
          10,
          40,
          a4Width,
          (a4Width / canvas1.width) * height
        );
        leftHeight -= height;
        position += height;
        if (leftHeight > 0) {
          setTimeout(createImpl, 500, canvas);
        } else {
          pdf.save(titleName + ".pdf");
          //下载完成后改变浏览器界面可视区域高度
          el.style.height = clientH + "px";

          loading.close();
        }
      }
    }
    let targetPage = pdf.internal.getNumberOfPages();
    //当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < a4HeightRef) {
      pdf.addImage(
        pageData,
        "JPEG",
        10,
        40,
        a4Width,
        (a4Width / canvas.width) * leftHeight
      );
      pdf.save(titleName + ".pdf");
      //下载完成后改变浏览器界面可视区域高度
      el.style.height = clientH + "px";
    } else {
      try {
        pdf.deletePage(0);
        setTimeout(createImpl, 500, canvas);
      } catch (err) {}
    }
  });
}
